package com.atwbj.langchain4jbeta3learndemo.controller;

import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;

import java.util.Base64;

/**
 * @description:
 * @author: wbj
 * @create: 2025-07-21 14:59
 **/
@RestController
@RequestMapping("/imageModel")
@Slf4j
public class ImageModelController {
    @Resource(name = "qwen-vl-max")
    private ChatLanguageModel chatModel;
    @Autowired
    private ResourceLoader resourceLoader;

   // 通过Base64编码将图片转化为字符串，结合ImageContent和TextContent一起发送到模型进行处理。
   @GetMapping(value = "/computeProblem")
    public String getImage() throws Exception {
         String base64Data = this.imageToBase64();
         //图文并茂，封装提问的图片和文字
         TextContent textContent = TextContent.from("请帮计算一下图片中的每一个题目，给出答案");
         ImageContent imageContent = ImageContent.from(base64Data);
         UserMessage userMessage = UserMessage.from(textContent, imageContent);
         ChatResponse chatResponse = chatModel.chat(userMessage);
         String result = chatResponse.aiMessage().text();



         System.out.println(result);

         return result;
   }

    //LangChain4j 中的 ImageContent.from(base64Data) 要求 Base64 字符串必须带有 MIME 类型前缀
    //例如 ...
    public String imageToBase64() throws Exception {
        String imagePath = "static/image/test.png";
        ClassPathResource resource = new ClassPathResource(imagePath);

        if (!resource.exists()) {
            throw new IOException("图片文件不存在，请检查路径是否正确: " + imagePath);
        }
        // 使用 try-with-resources 语句自动关闭资源
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] imageBytes = StreamUtils.copyToByteArray(inputStream);
            // 动态获取 MIME 类型
            MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
            String mimeType = mediaType.toString();

            return "data:" + mimeType + ";base64," + Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            throw new RuntimeException("读取图片文件时发生异常: " + imagePath, e);
        }



    }


}